const openDB = async () => {
  // 打开数据库连接
  var openRequest = await indexedDB.open("studentDB", 1);

  openRequest.onupgradeneeded = function (e) {
    console.log("更新数据库");
    // 创建一个对象存储空间
    var db = e.target.result;
    var store = db.createObjectStore("students", { keyPath: "id" });
    // 定义学生对象的索引
    store.createIndex("name", "name", { unique: false });
    store.createIndex("age", "age", { unique: false });
    store.createIndex("gender", "gender", { unique: false });
    store.createIndex("class", "class", { unique: false });
  };

  return new Promise((resolve, reject) => {
    try {
      openRequest.onsuccess = async (e) => {
        var db = e.target.result;
        console.log("数据库连接成功");
        resolve(db);
      };
    } catch (error) {
      console.error("Database error: ", error);
      reject();
    }
  });
};

// 添加学生
function addStudent(db, students) {
  var transaction = db.transaction(["students"], "readwrite");
  var store = transaction.objectStore("students");
  students.forEach((student, index) => {
    student.id = new Date().getTime() + index;
    store.add(student);
  });

  return new Promise((resolve, reject) => {
    try {
      transaction.oncomplete = function (e) {
        console.log("批量添加数据完成");
        resolve("success");
      };

      transaction.onerror = function (e) {
        console.error("批量添加数据出错");
      };
    } catch (error) {
      console.error("批量添加数据出错", error);
    }
  });
}

// 删除学生
function deleteStudent(db, id) {
  var transaction = db.transaction(["students"], "readwrite");
  var store = transaction.objectStore("students");
  var request = store.delete(id);
  try {
    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        console.log("Student deleted successfully");
        resolve();
      };
    });
  } catch (error) {
    console.log("🚀 ~ deleteStudent ~ error:", error);
  }
}

// 更新学生信息
async function updateStudent(db, id, newStudent) {
  var transaction = db.transaction(["students"], "readwrite");
  var store = transaction.objectStore("students");
  var request = store.get(id);

  request.onsuccess = function (e) {
    if (request.result) {
      var updatedStudent = Object.assign(request.result, newStudent);
      var updateRequest = store.put(updatedStudent);

      updateRequest.onsuccess = function (e) {
        alert("Student updated successfully");
      };

      updateRequest.onerror = function (e) {
        console.error("Error updating student: " + e.target.errorCode);
      };
    } else {
      console.log("Student not found");
    }
  };

  request.onerror = function (e) {
    console.error("Error fetching student: " + e.target.errorCode);
  };
}

// 查询学生
function getStudent(db, id) {
  var transaction = db.transaction(["students"]);
  var store = transaction.objectStore("students");
  var request = store.get(id);

  request.onsuccess = function (e) {
    if (request.result) {
      console.log("Student found: ", request.result);
    } else {
      console.log("Student not found");
    }
  };

  request.onerror = function (e) {
    console.error("Error fetching student: " + e.target.errorCode);
  };
}

// 遍历所有学生
function getAllStudents(db) {
  try {
    const transaction = db.transaction(["students"]);
    const store = transaction.objectStore("students");
    const request = store.openCursor();
    const students = [];

    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        const cursor = e.target.result;
        if (cursor) {
          students.push(cursor.value);
          cursor.continue();
        } else {
          resolve(students);
        }
      };
    });
  } catch (error) {
    console.log("🚀 ~ getAllStudents ~ error:", error);
  }
}

function getStudentByName(db, name) {
  console.log("🚀 ~ getStudentByName ~ name:", name);
  try {
    const transaction = db.transaction(["students"]);
    const store = transaction.objectStore("students");
    const index = store.index("name");
    const request = index.openCursor(name);
    const students = [];

    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        const cursor = e.target.result;
        if (cursor) {
          if (cursor.key.indexOf(name) === 0) {
            students.push(cursor.value);
          }
          cursor.continue();
        } else {
          resolve(students);
        }
      };
    });
  } catch (error) {
    console.log("🚀 ~ getAllStudents ~ error:", error);
  }
}

export {
  openDB,
  addStudent,
  deleteStudent,
  updateStudent,
  getStudent,
  getAllStudents,
  getStudentByName,
};
